﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Glacier.Lib.Mvc.Action;
using System.Threading;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace Glacier.Lib.Mvc
{
    /// <summary>
    /// Main entry of the MVC framework
    /// </summary>
    public static class MvcFramwork
    {
        /// <summary>
        /// Synchronized Calls the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public static ActionResult Call(ActionRequest request)
        {
            return GetController(request.Controller).Excute(request);
        }

        /// <summary>
        /// Asynchronous call
        /// </summary>
        /// <param name="request">The request.</param>
        public static void AsychCall(ActionRequest request)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc), request);
        }

        /// <summary>
        /// Registers the controller and view
        /// </summary>
        public static void Register()
        {
            _unityContainer.LoadConfiguration();
        }
        
        /// <summary>
        /// Gets the view.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public static IView GetView(String name)
        {
            return _unityContainer.Resolve<IView>(name);
        }

        /// <summary>
        /// Gets the controller.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public static IController GetController(String name)
        {
            return _unityContainer.Resolve<IController>(name);
        }

        private static IUnityContainer _unityContainer = new UnityContainer();

        private static void TaskProc(object obj)
        {
            ActionRequest request = obj as ActionRequest;

            ActionResult ret = GetController(request.Controller).Excute(request);

            if (request.CallBack != null)
            {
                request.CallBack(ret);
            }
        }
    }
}
